<template>
  <ul>
    <li v-for="item, index in discussData" :key="index" class="discuss-item">
      <img :src="item.image" alt="头像" style="width: 10%;border-radius: 50%;margin-right: 10px;" />
      <div style="width: 90%;">
        <div class="top-comment">
          <h3 style="margin: 0;">{{ item.username }}</h3>
          <p style="margin: 0;font-size: 12px;color: gray;">{{ item.content }}</p>
          <img src="/public/评论.svg" alt="" class="img-comment" @click="openCommentFnInput(item.id)">
        </div>
        <p style="margin-top: 10px;">{{ item.text }}</p>
        <el-input type="text" placeholder="请输入评论" v-if="userStore.commentInput === item.id" v-model="context">
          <template #append>
            <div>
              <el-button type="primary" @click="handleSubmit(item)">提交</el-button>
            </div>
          </template>
        </el-input>
        <el-button @click="openCommentFn(item.id)" v-if="item.children" link>{{ openCommentIndex ? '收起评论' : '展开评论'
        }}</el-button>
        <useComment :discussData="item.children" v-if="item.children && openCommentIndex === item.id" />
      </div>
    </li>
  </ul>
</template>
<script setup lang="ts">
import type { Comment } from '@/api/modules/weblog'
import { defineProps, ref } from 'vue'
import { useUserStore } from '@/stores/use'
import useComment from './useComment.vue'
import { createComment } from '@/api/modules'
import { inject } from 'vue'
import { ElMessage } from 'element-plus'
const getDiscussData = inject('getDiscussData', () => { })
defineProps(['discussData',]);

const userStore = useUserStore();
const context = ref('');
const openCommentIndex = ref<number | null>(null);
const openCommentFnInput = (index: number) => {
  if (userStore.commentInput !== index) {
    userStore.commentInput = index; // 展开输入框
  } else {
    userStore.commentInput = -1; // 收起输入框
  }
}
const openCommentFn = (index: number) => {
  if (openCommentIndex.value === index) {
    openCommentIndex.value = null;  // 收起当前评论
  } else {
    openCommentIndex.value = index;  // 展开当前评论
  }
}
const handleSubmit = async (item: Comment) => {
  if (!context.value) return
  if (!userStore.login) {
    ElMessage({
      message: '请先登录',
      type: 'error',
    })
    return
  }
  const params = {
    content: context.value,
    userId: userStore.id,
    parentId: item.id,
    articleId: item.articleId
  }
  await createComment(params)
  context.value = '';
  getDiscussData()
  userStore.commentInput = -1; // 收起输入框
  ElMessage({
    message: '评论成功',
    type: 'success',
  })
}
</script>

<style scoped>
.discuss-item {
  list-style: none;
  display: flex;
  padding: 10px;
  font-size: 14px;
}

.top-comment {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.img-comment {
  width: 20px;
  height: 20px;
}
</style>
